package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.dto.ManagedUserView;
import com.ruoyi.livedemo.entity.GoalItem;
import com.ruoyi.livedemo.entity.User;
import com.ruoyi.livedemo.entity.UserProfile;
import com.ruoyi.livedemo.mapper.AlbumMediaMapper;
import com.ruoyi.livedemo.mapper.DiaryEntryMapper;
import com.ruoyi.livedemo.mapper.GoalItemMapper;
import com.ruoyi.livedemo.mapper.LifeRecordMapper;
import com.ruoyi.livedemo.mapper.ReminderMapper;
import com.ruoyi.livedemo.mapper.StickyNoteMapper;
import com.ruoyi.livedemo.mapper.UserMapper;
import com.ruoyi.livedemo.mapper.UserProfileMapper;
import com.ruoyi.livedemo.mapper.UserSessionMapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * 用户管理相关业务。
 */
@Service
@RequiredArgsConstructor
public class AdminService {

    private final UserMapper userMapper;
    private final UserProfileMapper userProfileMapper;
    private final UserSessionMapper userSessionMapper;
    private final GoalItemMapper goalItemMapper;
    private final DiaryEntryMapper diaryEntryMapper;
    private final LifeRecordMapper lifeRecordMapper;
    private final ReminderMapper reminderMapper;
    private final StickyNoteMapper stickyNoteMapper;
    private final AlbumMediaMapper albumMediaMapper;

    public List<ManagedUserView> listUsers() {
        List<User> users = userMapper.findAll();
        if (CollectionUtils.isEmpty(users)) {
            return Collections.emptyList();
        }

        List<ManagedUserView> result = new ArrayList<>(users.size());
        for (User user : users) {
            Long userId = user.getId();
            UserProfile profile = userProfileMapper.findByUserId(userId);
            List<GoalItem> goals = goalItemMapper.findByUser(userId);
            if (goals == null) {
                goals = Collections.emptyList();
            }
            int goalCompleted = (int) goals.stream()
                    .filter(goal -> {
                        String status = goal.getStatus();
                        if (status != null && status.equalsIgnoreCase("COMPLETED")) {
                            return true;
                        }
                        if (status != null && status.equalsIgnoreCase("DONE")) {
                            return true;
                        }
                        Integer progress = goal.getProgressRatio();
                        return progress != null && progress >= 100;
                    })
                    .count();

            ManagedUserView view = ManagedUserView.builder()
                    .id(userId)
                    .username(user.getUsername())
                    .displayName(user.getDisplayName())
                    .email(user.getEmail())
                    .partnerName(profile != null ? profile.getPartnerName() : null)
                    .jobTitle(profile != null ? profile.getJobTitle() : null)
                    .contactPhone(profile != null ? profile.getContactPhone() : null)
                    .themePreference(user.getThemePreference())
                    .createdAt(user.getCreatedAt())
                    .lastLoginAt(userSessionMapper.findLatestLogin(userId))
                    .goalTotal(goals.size())
                    .goalCompleted(goalCompleted)
                    .diaryCount((int) diaryEntryMapper.countByUser(userId))
                    .lifeRecordCount((int) lifeRecordMapper.countByUser(userId))
                    .reminderCount((int) reminderMapper.countByUser(userId))
                    .noteCount((int) stickyNoteMapper.countByUser(userId))
                    .albumCount((int) albumMediaMapper.countByUser(userId))
                    .build();
            result.add(view);
        }
        return result;
    }
}
